import { reqlogin } from "../../http/api"
import { Toast } from "antd-mobile"
//State
const initState = {
    //初始化一个数据
    user:{
        phone:'',
        password:''
    },
    userInfo:sessionStorage.getItem('userInfo')?JSON.parse(sessionStorage.getItem('userInfo')):{}
}
//action type 
const TYPES = {
    //2修改user type
    LOGIN_CHANGE_USER:'LOGIN_CHANGE_USER',
    LOGIN_CHANGE_USERINFO:'LOGIN_CHANGE_USERINFO'
}
//reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        //3 修改user{type:'xx,key,value}
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            }
            // userInfo action = {type:'LOGIN_CHANGE_USERINFO'}
            case TYPES.LOGIN_CHANGE_USERINFO:
                return{
                    ...state,
                    userInfo:action.userInfo
                }
        default:
            return state;
    }
}
//action creator
export const actions = {
    //4修改user action
    changeUser:(key,value)=>({type:TYPES.LOGIN_CHANGE_USER,key,value}),
    changeUserInfo:userInfo=>{
        if(userInfo.token){
            sessionStorage.setItem('userInfo',JSON.stringify(userInfo))
        }else{
            sessionStorage.removeItem('userInfo')
        }
        return {type:TYPES.LOGIN_CHANGE_USERINFO,userInfo:userInfo}
    },

    //5登录的逻辑
    doLogin:(push)=>{
        return (dispatch,getState)=>{
            reqlogin(getUser(getState())).then(res=>{
                if(res.data.code===200){
                    Toast.show({
                        content:res.data.msg
                    })
                    //存信息
                    dispatch(actions.changeUserInfo(res.data.list))
                    //跳转
                    push('/index/home')
                }
            })
        }
    }

}

//selector导出数据给组件
export const getUser = state=>state.login.user; 
//导出userInfo
export const getUserInfo = state=>state.login.userInfo; 

//导出
export default reducer;